<?php

namespace Controller;
use Core\Controller;
use Core\Exception;
use mtyUser\UserRole;
use UserModel;
use Service\ResponseService;
use Validator\UserValidator;
use Service\ProductService;
/**
 * 移动端，微信端控制器基类
 * Class Mobile
 * @package Controller
 */
class Mobile extends Controller
{

    /**
     * 需要登录权限的控制器
     * 子类集成，以实现登录判断
     * ‘*’号代表改控制下所有action都要登录权限(全部小写)
     * @var array
     */

    protected $needLoginActions = [];

    /**
     * 需要实名认证的控制器
     * 子类集成，以实现登录判断
     * ‘*’号代表改控制下所有action都要登录权限(全部小写)
     * @var array
     */
    protected $needAttestActions = [];


    /**
     * 是否需要传入订单号
     * 子类集成，以实现特价商品通讯
     * ‘*’号代表改控制下所有action都要登录权限(全部小写)
     * @var array
     */
    protected $needOrderActions = [];

    /**
     * 用户信息
     * @var array
     */
    public $userInfo = [];

    /**
     * 用户资金账号信息
     * @var array
     */
    public $user_bank = [];

    /**
     * 用户实名信息
     * @var array
     */
    public $user_auth = [];


    /**
     * 特价商品信息
     * @var array
     */
    public $discountOrder = [];

    /**
     * 页面title
     * @var string
     */
    public $title = '木头云综合交易平台';


    public $order_number = '';

    public $user_role = array();

    /**
     * 初始化
     * @throws
     */
    public function init()
    {
        parent::init();
        $this->getUserBySession();
        $this->needLoginCheck();
        $this->needAttstCheck();
        $this->needOrderCheck();    //特价商品：不做登录态，用订单号通讯
        if($this->getRequest()->isGet()){
            $data['userInfo'] = $this->userInfo;
            $this->getView()->assign($data);
        }

    }

    /**
     *  页面渲染
     */
    public function view($data = [])
    {
        if( !isset($data['title']) ){
            $data['title'] = $this->title;
        }
        // 处理版本号问题
        $data['jsVersion'] = DEBUG ? date('YmdHis') : date('YmdHis');
//        dump($data);
        ResponseService::view($this, $data);
    }


    /**
     *  ajax返回
     */
    public function json($code='', $msg='', $data = [], $debugMsg='')
    {
        if($code == 1 AND $msg ==''){
           $msg = '操作成功' ;
        }
        $formatData['data'] = $data;
        ResponseService::json($code, $msg, $formatData,'', $debugMsg);
    }


    /**
     * 错误提示
     * @param code (1：成功，其他code根据错误信息表)
     * @param $msg
     * @param string $url
     * @throws
     */
    public function tip($code, $msg ='', $url = '')
    {
        if($code == 1){
            // 成功提示 todo
            throw new Exception(1, $msg, ['redirectUrl' => $url]);
        }else{
            throw new Exception($code, $msg, ['redirectUrl' => $url]);
        }

    }
    /**
     * 通过session获取user登录态
     * @throws
     */
    private function getUserBySession()
    {
        $userInfo   = $this->request->getSession('userInfo');
        if (is_object($userInfo)){
            $userInfo = $userInfo->toArray();
        }

        if(!empty($userInfo['id']) AND  !empty($userInfo['expireTime']) AND $userInfo['expireTime'] > time()){
            $mUser = new UserModel();
            $userInfo = $mUser->getUserById($userInfo['id'],'*');
            if(!empty($userInfo)){
                // 用户已注销，强制退出
                if($userInfo['is_logoff'] == 1){
                    $this->request->unsetSession('userInfo');
                    throw new Exception(10004);
                }

                $userInfo['expireTime'] =  time() + 60 * 60;

                $user_role = $this->user_role = (new UserRole())->getUserRole($userInfo['id'])['data'];

                if (in_array('SPECIAL_BUYER', $user_role)){
                    $this_role = 'SPECIAL_BUYER';
                }elseif(in_array('SPECIAL_SELLER', $user_role)){
                    $this_role = 'SPECIAL_SELLER';
                }else{
                    $this_role = array_pop($user_role);
                }

                $userInfo['role'] = $this_role;
                #注意：这里的curr_identity是切换的当前身份 （因为后期添加的字段刚好与这个变量冲突了，只能这样写了，可以的话后期优化）
                $userInfo['curr_identity'] = $userInfo['role'];//当前切换的身份（用于切换身份）
                if ($userInfo['role']=='ORD_SELLER'){
                    $userInfo['curr_identity'] = 'ORD_'.$userInfo['ord_role'];
                }
//                $userInfo['role'] = $mUser->getRoleById($userInfo['id']);   //用户固定身份（相当于最高权限身份，移动端需要本值控制函数调用权限、内容显示权限）

                $this->request->setSession('userInfo', $userInfo);
                $this->userInfo = $userInfo;

                //资金账户
                $Auth = (new \mtyUser\Auth());
                $this->user_bank = $Auth->getUserBank($this->userInfo['id']);

                //实名信息
                $true_auth = $Auth->hasTrueAuth($this->userInfo['id']);
                if ($true_auth['status'] == 'PASSED'){
                    if ($true_auth['type'] == 'PERSON'){
                        $auth_data = (new \UserAuthPersonModel())->where(['id' => $true_auth['auth_id']])->find();
                    }else{
                        $auth_data = (new \UserAuthCompanyModel())->where(['id' => $true_auth['auth_id']])->find();
                    }
                    $auth_data = empty($auth_data) ? array() : $auth_data->toArray();
                }
                $this->user_auth = [
                    'has_auth'  => $true_auth['status'] == 'PASSED' ? true : false, //是否
                    'type'      => $true_auth['type'],  //PERSON个人 COMPANY企业
                    'rel_id'    => $true_auth['id'],  //关联ID
                    'auth_id'   => $true_auth['auth_id'],  //实名ID
                    'auth_data' => $auth_data,  //实名信息
                ];

            }else{
                $this->request->unsetSession('userInfo');
            }
        }else{
            $this->request->unsetSession('userInfo');
        }
    }

    /**
     * 判断控制器是否需要登录
     * @throws
     */
    private function needLoginCheck()
    {
        $needLogin = false;
        if( !empty($this->needLoginActions) ){
            if( in_array('*', $this->needLoginActions)){
                $needLogin =  true;
            }else{
                $actionName = $this->getRequest()->getActionName();
                if(!empty($actionName) AND in_array($actionName, $this->needLoginActions)){
                    $needLogin = true;
                }
            }
        }

        if( $needLogin AND empty( $this->userInfo['id'] )) {
            if ($this->request->isAjax()){                 //如果ajax调用方法，请统一使用POST
                throw new Exception(10003,'请登录');
            }else{
                //非POST请求，认为是普通直接访问页面，故直接跳转至登录页面
                $this->redirect('/mobile/auth/login');
                die();
            }
        }
    }

    /**
     * 判断控制器是否实名认证
     * @throws
     */
    private function needAttstCheck()
    {
        $needAttest = false;
        if( !empty($this->needAttestActions) ){
            if( in_array('*', $this->needAttestActions)){
                $needAttest =  true;
            }else{
                $actionName = $this->getRequest()->getActionName();
                if(!empty($actionName) AND in_array($actionName, $this->needLoginActions)){
                    $needAttest = true;
                }
            }
        }

        if ($needAttest){
            $attestCheck = (new UserValidator())->setConfig(['catchException' => false])->validate($this->userInfo, ['id' => 'isAttest']);
            if( 1 !== $attestCheck['code']){
                if ($this->request->isAjax()){                 //如果ajax调用方法，请统一使用POST
                    throw new Exception(10107,'请完成实名认证');
                }else{
                    //非POST请求，认为是普通直接访问页面，故直接跳转至登录页面
                    $this->tip(10107,'请完成实名认证','/mobile/attest/index');
                }
            }
        }


    }

    /**
     * 重新存储一次userInfo
     */
    protected function updateUserInfo($newUserInfo){
        $this->request->setSession('userInfo', $newUserInfo);
    }



    /**
     * 【特价商品】判断控制器是否传入订单号
     * @throws
     */
    private function needOrderCheck()
    {
        $needOrder = false;
        if ($this->request->isAjax()){
            $this->order_number = $this->request->post('order_number');
        }else{
            $this->order_number = $this->request->get('order_number');
        }


        if( !empty($this->needOrderActions) ){
            if( in_array('*', $this->needOrderActions)){
                $needOrder =  true;
            }else{
                $actionName = $this->getRequest()->getActionName();
                $this->needOrderActions = array_map(function ($value){
                    return strtolower($value);
                }, $this->needOrderActions);
                if(!empty($actionName) AND in_array($actionName, $this->needOrderActions)){
                    $needOrder = true;
                }
            }
        }


        if( $needOrder AND empty($this->order_number)) {
            if ($this->request->isAjax()){                 //如果ajax调用方法，请统一使用POST
                throw new Exception(11108);
            }else{
                //非POST请求，认为是普通直接访问页面，故直接跳转至登录页面

                $this->redirect('/discount/discountlist/list');
            }
        }

        if ($needOrder){
            //通过订单解析订单信息、用户信息
            $order = (new \ProductDiscountOrderModel())->getOneByOrder($this->order_number);
            if (empty($order)){
                if ($this->request->isAjax()){                 //如果ajax调用方法，请统一使用POST
                    throw new Exception(11108);
                }else{
                    //非POST请求，认为是普通直接访问页面，故直接跳转至登录页面
                    $this->redirect('/discount/discountlist/list');
                }
            }
            if ($order['order_yst_id']){
                $order_yst = (new \ProductDiscountYstOrderModel())->getOneById($order['order_yst_id']);
                if (!$this->request->isAjax()){                 //如果ajax调用方法，请统一使用POST
                    if ($order_yst['status'] != 'INIT'){
                        $this->redirect('/discount/order/detail?order_number='.$this->order_number);
                    }
                }
            }

            $userInfo = (new UserModel())->getUserById($order['user_id'],'*');
            $this->userInfo = $userInfo;
            $this->discountOrder = $order;
        }
    }

}